<template>
  <div class="personnel-table-container">
    <div class="table-toolbar">
      <div class="left-buttons">
        <el-button type="primary" @click="handleBatchAdd">批量添加</el-button>
        <el-button type="primary" @click="handleAdd">添加人员</el-button>
      </div>

      <div class="search-area">
        <el-input
          v-model="searchQuery"
          placeholder="搜索人员姓名/编码"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleSearch">
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>

      <el-button circle @click="refreshList">
        <el-icon><Refresh /></el-icon>
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="filteredPersonnelList"
      style="width: 100%"
      border
      row-key="id"
    >
      <el-table-column type="index" width="60" label="序号" />
      <el-table-column prop="personnelCode" label="人员编码" width="120" />
      <el-table-column prop="personnelName" label="人员姓名" width="120" />
      <el-table-column prop="supplierName" label="供应商" min-width="150" />
      <el-table-column prop="levelName" label="级别" width="100" />
      <el-table-column prop="startDate" label="开始日期" width="120" />
      <el-table-column prop="endDate" label="结束日期" width="120" />
      <el-table-column prop="monthlyRate" label="人月单价" width="120">
        <template #default="scope">
          {{ scope.row.monthlyRate ? scope.row.monthlyRate.toFixed(2) : "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <status-tag :status="scope.row.status" :status-name="scope.row.statusName" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleViewDetail(scope.row)"> 查看 </el-button>
          <el-button type="danger" link @click="handleRemove(scope.row)"> 移除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加人员对话框 -->
    <add-personnel-dialog
      v-model:visible="addDialogVisible"
      :is-batch="isBatchAdd"
      :order-id="orderId"
      @success="onAddSuccess"
    />

    <!-- 人员详情抽屉 -->
    <personnel-detail
      v-model:visible="detailDrawerVisible"
      :personnel-data="currentPersonnel"
      @refresh="onDetailRefresh"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watch, onMounted } from "vue";
import { Search, Refresh } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import StatusTag from "@/components/StatusTag/index.vue";
import { getOrderPersonnelList, removeOrderPersonnel } from "@/api/attendance/orderPersonnel";
import type { OrderPersonnelVO } from "@/types/attendance/order/personnelRelation";
import AddPersonnelDialog from "./AddPersonnelDialog.vue";
import PersonnelDetail from "./PersonnelDetail.vue";

export default defineComponent({
  name: "OrderPersonnelTable",
  components: {
    Search,
    Refresh,
    StatusTag,
    AddPersonnelDialog,
    PersonnelDetail
  },
  props: {
    orderId: {
      type: Number,
      required: true
    }
  },
  setup(props) {
    // 状态
    const loading = ref(false);
    const personnelList = ref<OrderPersonnelVO[]>([]);
    const searchQuery = ref("");
    const addDialogVisible = ref(false);
    const detailDrawerVisible = ref(false);
    const currentPersonnel = ref<OrderPersonnelVO | null>(null);
    const isBatchAdd = ref(false);

    // 过滤后的人员列表
    const filteredPersonnelList = computed(() => {
      if (!searchQuery.value) return personnelList.value;

      const query = searchQuery.value.toLowerCase();
      return personnelList.value.filter(
        item =>
          (item.personnelName && item.personnelName.toLowerCase().includes(query)) ||
          (item.personnelCode && item.personnelCode.toLowerCase().includes(query))
      );
    });

    // 初始化
    onMounted(() => {
      if (props.orderId) {
        fetchPersonnelList();
      }
    });

    watch(
      () => props.orderId,
      newOrderId => {
        if (newOrderId) {
          fetchPersonnelList();
        }
      }
    );

    // 方法
    async function fetchPersonnelList() {
      if (!props.orderId) return;

      loading.value = true;
      try {
        // 调用真实API获取数据
        const { data } = await getOrderPersonnelList(props.orderId);
        personnelList.value = data;
      } catch (error) {
        console.error("获取人员列表失败:", error);
      } finally {
        loading.value = false;
      }
    }

    function handleSearch() {
      // 搜索逻辑已通过计算属性实现
    }

    function refreshList() {
      fetchPersonnelList();
    }

    function handleAdd() {
      isBatchAdd.value = false;
      addDialogVisible.value = true;
    }

    function handleBatchAdd() {
      isBatchAdd.value = true;
      addDialogVisible.value = true;
    }

    function onAddSuccess() {
      refreshList();
    }

    function onDetailRefresh() {
      refreshList();
    }

    function handleViewDetail(row: OrderPersonnelVO) {
      currentPersonnel.value = row;
      detailDrawerVisible.value = true;
    }

    function handleRemove(row: OrderPersonnelVO) {
      ElMessageBox.confirm(`确定要移除人员 "${row.personnelName}" 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            // 调用真实API删除数据
            await removeOrderPersonnel(row.id);
            ElMessage.success("移除人员成功");
            refreshList();
          } catch (error) {
            console.error("移除人员失败:", error);
          }
        })
        .catch(() => {
          // 用户取消操作
        });
    }

    return {
      loading,
      personnelList,
      searchQuery,
      filteredPersonnelList,
      addDialogVisible,
      detailDrawerVisible,
      currentPersonnel,
      isBatchAdd,
      fetchPersonnelList,
      handleSearch,
      refreshList,
      handleAdd,
      handleBatchAdd,
      onAddSuccess,
      onDetailRefresh,
      handleViewDetail,
      handleRemove
    };
  }
});
</script>

<style scoped>
.personnel-table-container {
  padding: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-toolbar .left-buttons {
  display: flex;
  gap: 8px;
}

.search-area {
  flex: 1;
  margin: 0 20px;
  max-width: 350px;
}
</style>
